<?php 

namespace App\Http\Middleware;

use Closure;
use Illuminate\Routing\Redirector;
use Illuminate\Http\Request;
use App;

class Language
{
    public function handle($request, Closure $next)
    {
    	$locale = $request->segment(1);
    	if (!array_key_exists($locale, config('app.locales'))) {
    		$segments = $request->segments();
    		$segments[0] = config('app.fallback_locale');

    		return redirect(implode('/', $segments));
    	}

    	App::setLocale($locale);

    	return $next($request);
    }

}